﻿using BBCore.Application.Interface;
using BBCore.Application.Samples;
using Microsoft.AspNetCore.Components;
using System.Diagnostics.CodeAnalysis;
namespace BBCore.Server.Components.Pages.Samples
{
    public partial class Seckill
    {
        [NotNull]
        [Inject] IFlashSaleService? IFlashSaleService {  get; set; }
        private void InitializeData()
        {
            IFlashSaleService.InitializeData();
            System.Console.WriteLine("数据初始化完成");
        }
        private async Task StartSimulation()
        {
            var tasks = new List<Task>();
            for (int i = 0; i < 100; i++)
            {
                int currentI = i+1; // 创建一个新的变量保存当前 i 的值
                tasks.Add(Task.Run(() =>
                {
                    var product = IFlashSaleService.GetProduct();
                    if (product != null && product.Stock <= 0)
                    {
                        System.Console.WriteLine($"用户 {currentI} 商品已卖空，秒杀失败");
                        return;
                    }

                    var result = IFlashSaleService.TrySeckill(product!.Id);
                    var message = result ? $"用户 {currentI} 秒杀成功,恭喜恭喜恭喜恭喜恭喜恭喜恭喜恭喜" : $"用户 {currentI} 秒杀失败";
                    System.Console.WriteLine(message);
                }));
            }

            await Task.WhenAll(tasks);
        }
    }
}
